package org.l.qiao.connect;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

import org.apache.log4j.Logger;

public class Excel implements FileControl {

    Logger LOGGER = Logger.getLogger(Excel.class);

    private Workbook workbook = null;

    public Excel() {
    }

    public boolean setFile(String excelfile) {
        boolean ok = false;
        try {
            workbook = Workbook.getWorkbook(new File(excelfile));
            ok = true;
        } catch (Exception e) {
            LOGGER.error("文件操作错误：" + e.getMessage());
        }
        return ok;
    }

    public boolean isReady() {
        return workbook != null;
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    public List getRows(Object obj) {
        List rowobj = new ArrayList();
        Sheet sheet = workbook.getSheet(0);
        int colm = sheet.getColumns();
        int i, j;
        String[] headers = new String[colm];
        Cell[] headercells = sheet.getRow(0);
        for (i = 0; i < headercells.length; i++) {
            headers[i] = headercells[i].getContents().toLowerCase();
        }
        DataMap dm = new DataMap();
        for (i = 1; i < sheet.getRows(); i++) {
            Object newobj = null;
            try {
                newobj = obj.getClass().newInstance();
            } catch (Exception e) {
                LOGGER.error("重新实例化对象时出错：" + e.getMessage());
            }
            Cell[] cells = sheet.getRow(i);
            for (j = 1; j < headers.length; j++) {
                try {
                    dm.Mapping(headers[j], cells[j].getContents(), newobj);
                } catch (Exception e) {
                    LOGGER.error("对象值映射时出错：" + e.getMessage());
                }
            }
            rowobj.add(newobj);
        }
        return rowobj;
    }

    public void close() {
        if (workbook != null) {
            workbook.close();
            workbook = null;
        }
    }
}
